package com.pocket.demo.core.security.filters;

import com.pocket.demo.base.consts.RequestConst;
import com.pocket.demo.core.context.TokenContext;
import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * @author zhaozhile
 */
public class TokenContextFilter extends OncePerRequestFilter implements Ordered {

    private static final Logger LOGGER = LoggerFactory.getLogger(TokenContextFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain){
        String token = request.getHeader(RequestConst.HEAD_TOKEN);
        try {
            if (StringUtils.isNotBlank(token)){
                LOGGER.debug("request【{}】token 【{}】, skip", request.getRequestURI(), token);
                TokenContext.setToken(token);
            }
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            LOGGER.error("Token ContextFilter error", e);
        } finally {
            TokenContext.remove();
        }
    }


    @Override
    public int getOrder() {
        return 1;
    }
}
